package cn.com.nes.site.service.product.impl;

import cn.com.nes.common.exception.MissBusinessParameterException;
import cn.com.nes.common.util.CopyUtils;
import cn.com.nes.common.util.OssUtil;
import cn.com.nes.common.util.id.AgentIdEnum;
import cn.com.nes.common.util.id.AgentIdUtils;
import cn.com.nes.mybatis.agent.ope.entity.GGoods;
import cn.com.nes.mybatis.agent.ope.mapper.GGoodsMapper;
import cn.com.nes.mybatis.agent.system.entity.CompanyMerchant;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.dto.product.DeviceModelDTO;
import cn.com.nes.site.entity.dto.product.GGoodsDTO;
import cn.com.nes.site.entity.dto.product.IsSblxNameplateConfigDTO;
import cn.com.nes.site.entity.dto.product.ProductSeriesAndEnergyDTO;
import cn.com.nes.site.entity.em.DeleteEnum;
import cn.com.nes.site.entity.vo.product.GGoodsVO;
import cn.com.nes.site.entity.vo.product.IsSblxNameplateConfigVO;
import cn.com.nes.site.modules.agent.grant.AgentGrant;
import cn.com.nes.site.service.product.GGoodsService;
import cn.com.nes.site.service.product.IsSblxNameplateConfigService;
import cn.com.nes.site.service.product.ProductSeriesAndEnergyService;
import cn.com.nes.site.service.product.SblxService;
import cn.com.nes.site.service.product.bo.QueryProductSeriesAndEnergyBO;
import cn.com.nes.site.service.product.dto.ProductDTO;
import cn.com.nes.site.service.system.company.CompanyMerchantService;
import cn.com.nes.site.service.system.dict.TParamService;
import cn.com.nes.site.service.workOrder.dto.InstallOrderEquipmentDTO;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品（产品）维护实现类
 *
 * @Author: ShenWei
 * @Date: 2024/03/28/9:47
 */
@Slf4j
@Service
public class GGoodsServiceImpl extends ServiceImpl<GGoodsMapper, GGoods> implements GGoodsService {
    private static final String IS_DELETE_YES = "1";
    private static final String IS_DELETE_NO = "0";
    public static final String GOODS_FIELDS_SBLX = "sblx"; // g_goods表字段 sblx
    public static final String GOODS_FIELDS_ENERGY_TYPE = "energy_type"; // g_goods表字段 energy_type

    @Resource
    GGoodsMapper gGoodsMapper;

    @Resource
    ProductSeriesAndEnergyService productSeriesAndEnergyService;

    @Resource
    IsSblxNameplateConfigService isSblxNameplateConfigService;

    @Resource
    TParamService tParamService;

    @Resource
    SblxService sblxService;

    @Resource
    private AgentGrant agentGrant;

    @Resource
    private CompanyMerchantService companyMerchantService;

    @Override
    public PageData getParamFields(String dbName) {
        List<String> paramFields = gGoodsMapper.getParamFields(dbName);
        Map<String, Object> map = new HashMap<>();
        map.put("paramFields", paramFields);

        return PageData.ok(map);
    }

    @Override
    public Boolean checkCanUpdate(String fields, String value) {
        QueryWrapper<GGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("isdelete", "0");
        wrapper.eq(fields, value);

        Integer count = this.baseMapper.selectCount(wrapper);

        if (0 == count) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageData saveGoods(GGoodsVO vo) {
        String userId="";
        String companyId="";
        if(ObjectUtil.isNotNull(vo.getUserInfo())){
             userId = vo.getUserInfo().getId();
             companyId = vo.getUserInfo().getCompanyId();
        }else{
            companyId=vo.getCompanyId();
        }
        Date now = new Date();
        String id = vo.getUuid();

        if (StrUtil.isNotBlank(id) && !checkProductBelongToCompany(id, companyId)) {
            return PageData.error("当前产品不属于本公司,修改失败!");
        }

        GGoods goods = new GGoods();
        BeanUtils.copyProperties(vo, goods);

        // 新增
        if (StrUtil.isBlank(id)) {
            goods.setCompanyId(companyId);
            goods.setCreateUid(userId);
            goods.setCreateTime(now);
            goods.setIsdelete(IS_DELETE_NO);
            goods.setSblx(AgentIdUtils.createID(AgentIdEnum._sblx_code));    // 生成设备类型编码
        }
        // 保存
        goods.setModifyUid(userId);
        goods.setModifyTime(now);
        this.saveOrUpdate(goods);
        id = goods.getUuid();

        // 保存配置字段
        String sqlStr = "";
        List<GGoodsVO.FieldsParam> fieldsParamList = vo.getFieldsParamList();
        if (CollectionUtil.isNotEmpty(fieldsParamList)) {
            Map<String, String> map = saveGoodsConfig(fieldsParamList, id);
            if (StrUtil.isNotBlank(map.get("msg"))) {
                return PageData.error("字段【" + map.get("msg") + "】重复,请修改后再提交");
            }
            sqlStr = map.get("sqlStr");
        }
        // 推送给t_sblx表
        if (StrUtil.isNotBlank(vo.getOperateUserCompanyType()) && "01".equals(vo.getOperateUserCompanyType())) {
            BeanUtils.copyProperties(goods, vo);
            sblxService.pushSblx(vo, sqlStr);
        }
        // 返回id
        return PageData.ok("id", id);
    }

    // 保存参数字段
    private Map<String, String> saveGoodsConfig(List<GGoodsVO.FieldsParam> configList, String id) {
        Map<String, String> map = new HashMap<>();
        // 字段判重
        for (GGoodsVO.FieldsParam fieldsParam : configList) {
            String field = fieldsParam.getSblxField();
            Long count = configList.stream().filter(n -> field.equals(n.getSblxField())).count();
            if (count > 1) {
                map.put("msg", field);
                return map;
            }
        }
        // 更新配置字段的值
        List<String> collect = configList.stream().map(n -> n.getSblxField() + " = '" + n.getValue() + "'").collect(Collectors.toList());
        String sqlStr = String.join(",", collect);

        gGoodsMapper.updateFields(sqlStr, id);
        map.put("sqlStr", sqlStr);
        return map;
    }

    @Override
    public PageData getGoodsPage(GGoodsVO vo) throws Exception {
        // 准备公共参数
        Page<GGoodsDTO> page = new Page<>(vo.getPageid(), vo.getPagesize());
        Set<String> myCompanyProductIdSet = new HashSet<>();
        Set<String> queryAgentGrantProductIdSet = new HashSet<>();

        // 1、处理查询方式 - 政府商机查询产品分页
        if (CollectionUtil.isNotEmpty(vo.getProductEnergyIdList())
                || CollectionUtil.isNotEmpty(vo.getProductBrandIdList())
                || CollectionUtil.isNotEmpty(vo.getEnergyTypeList())) {
            // 有任何一个条件不为null,说明需要以【能源类型】的体系做查询
            return PageData.ok(page, getGoodsPageByEnergyType(vo));
        }

        // 2、产品管理页面查询产品分页 - 未传入品牌id查询产品分页
        if (ObjectUtil.isNull(vo.getBrandId())) {
            myCompanyProductIdSet = queryMyCompanyProductId(null, vo.getOperateUserCompanyId());
            queryAgentGrantProductIdSet = queryAgentGrantProductId(null, vo.getOperateUserCompanyId());
        } else {
            // 3、产品管理页面查询产品分页 - 以品牌id查询产品分页
            // 查询品牌子节点id
            List<Long> brandChildIds = productSeriesAndEnergyService.getAllChildIds(vo.getBrandId(), true);
            // 查询品牌节点详情
            ProductSeriesAndEnergyDTO brandDetail = productSeriesAndEnergyService.getDetailById(vo.getBrandId());
            // 如果是以本公司的品牌查询
            if (brandDetail.getCompanyId().equals(vo.getOperateUserCompanyId())) {
                myCompanyProductIdSet = queryMyCompanyProductId(brandChildIds, vo.getOperateUserCompanyId());
            } else {
                // 如果是以上级厂商的品牌查询
                queryAgentGrantProductIdSet = queryAgentGrantProductId(brandChildIds, vo.getOperateUserCompanyId());
            }
        }

        // 查询能源分类子节点id
        List<Long> energyTypeChildIds = new ArrayList<>();
        if (ObjectUtil.isNotNull(vo.getEnergyType())) {
            energyTypeChildIds = productSeriesAndEnergyService.getAllChildIds(vo.getEnergyType(), true);
        }

        // 最终查询
        Set<String> productUuidSet = new HashSet<>();
        productUuidSet.addAll(myCompanyProductIdSet);
        productUuidSet.addAll(queryAgentGrantProductIdSet);

        if (CollectionUtil.isEmpty(productUuidSet)) {
            return PageData.ok(page, new ArrayList<>());
        }

        QueryWrapper<GGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("uuid", productUuidSet);
        if (CollectionUtil.isNotEmpty(energyTypeChildIds)) queryWrapper.in("energy_type", energyTypeChildIds);
        if (StrUtil.isNotBlank(vo.getGoodsName())) queryWrapper.like("goodsName", vo.getGoodsName());
        if (StrUtil.isNotBlank(vo.getTabPosition())) queryWrapper.eq("tabPosition", vo.getTabPosition());
        if (ObjectUtil.isNotNull(vo.getEnable())) queryWrapper.eq("enable", vo.getEnable());
        queryWrapper.orderByDesc("modifyTime");
        Page<GGoods> gGoodsPage = new Page<>(vo.getPageid(), vo.getPagesize());
        IPage<GGoods> productPage = this.baseMapper.selectPage(gGoodsPage, queryWrapper);
        // 处理返回值
        List<GGoodsDTO> gGoodsDTOList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(productPage.getRecords())) {
            gGoodsDTOList = CopyUtils.copyList(productPage.getRecords(), GGoodsDTO.class);
            // 设置出参字段
            setResponseParams(gGoodsDTOList, true);
        }

        return PageData.ok(page, gGoodsDTOList);
    }

    @Override
    public PageData getGoodsDetail(GGoodsVO vo) throws Exception {
        GGoodsDTO gGoodsDTO = getGoodsDetailByUuid(vo.getUuid());

        // 组装到列表中
        Page<GGoodsDTO> page = new Page<>(vo.getPageid(), vo.getPagesize());
        List<GGoodsDTO> goodsList = new ArrayList<>();
        goodsList.add(gGoodsDTO);

        return PageData.ok(page, goodsList);
    }

    @Override
    public GGoodsDTO getGoodsDetailBySblx(String sblx) throws Exception {
        // 查询产品主体
        QueryWrapper<GGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("sblx", sblx);
        GGoods gGoods = this.getOne(wrapper);
        if (ObjectUtil.isNull(gGoods)) {
            throw new Exception("产品不存在!sblx = " + sblx);
        }
        // 转换格式
        GGoodsDTO gGoodsDTO = new GGoodsDTO();
        BeanUtils.copyProperties(gGoods, gGoodsDTO);

        // 设置出参字段
        List<GGoodsDTO> goodsList = new ArrayList<>();
        goodsList.add(gGoodsDTO);
        setResponseParams(goodsList, true);

        return goodsList.get(0);
    }

    // 设置出参字段
    private void setResponseParams(List<GGoodsDTO> goodsList, Boolean getPic) {
        if (CollectionUtil.isEmpty(goodsList)) {
            return;
        }
        for (GGoodsDTO goodsDTO : goodsList) {
            // 品牌类型
            Long brandId = goodsDTO.getBrandId();
            ProductSeriesAndEnergyDTO brandDetail = productSeriesAndEnergyService.getDetailById(brandId);
            goodsDTO.setBrandName(brandDetail.getNodeName());

            // 能源类型
            Long energyType = goodsDTO.getEnergyType();
            ProductSeriesAndEnergyDTO energyTypeDetail = productSeriesAndEnergyService.getDetailById(energyType);
            goodsDTO.setEnergyTypeName(energyTypeDetail.getNodeName());

            // 产品单位
            String unit = goodsDTO.getUnit();
            String unitName = tParamService.getNameByParamTypeAndValue("304", unit);
            goodsDTO.setUnitName(unitName);

            // 产品图片
            if (getPic && StrUtil.isNotBlank(goodsDTO.getLogo())) {
                List<String> picRealUrlList = new ArrayList<>();

                String logos = goodsDTO.getLogo();
                log.debug("开始查询图片真实路径,原始图片:" + logos);
                List<String> picUrlList = Arrays.asList(logos.split(";"));
                for (String picUrl : picUrlList) {
                    String picRealUrl = OssUtil.getImgSignURL(picUrl, 1);
                    picRealUrlList.add(picRealUrl);
                }
                String picRealUrls = String.join(";", picRealUrlList);
                log.debug("图片真实路径:" + picRealUrls);
                goodsDTO.setLogoRealUrl(picRealUrls);
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public PageData delGoods(GGoodsVO vo) {
        String uuid = vo.getUuid();
        if (StrUtil.isBlank(uuid)) {
            return PageData.error("请传入产品uuid");
        }
        if (!checkProductBelongToCompany(uuid, vo.getOperateUserCompanyId())) {
            return PageData.error("当前产品不属于本公司,修改失败!");
        }

        // 修改内容
        GGoods gGoods = new GGoods();
        gGoods.setIsdelete(IS_DELETE_YES);
        gGoods.setModifyTime(new Date());
        gGoods.setModifyUid(vo.getUserInfo().getId());
        // 匹配条件
        QueryWrapper<GGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("uuid", uuid);

        boolean isUpdate = this.update(gGoods, wrapper);

        // 删除t_sblx
        GGoods goods = this.getOne(wrapper);
        sblxService.delSblx(goods.getSblx(), vo);

        if (isUpdate) {
            return PageData.ok("删除成功!");
        }
        return PageData.error("删除失败!");
    }

    @Override
    public List<GGoodsDTO> getGoodsListByCompanyId(String companyId) {
        List<GGoodsDTO> gGoodsList = gGoodsMapper.getGoodsListByCompanyId(companyId);
        setResponseParams(gGoodsList, true);
        return gGoodsList;
    }

    @Override
    public List<String> getGoodsIdListByEquipmentType(String companyId, String equipmentType) throws Exception {
        // 获取用户所选的设备能源分类id
        List<String> goodsIdList = new ArrayList<>();
        if (StrUtil.isNotBlank(equipmentType) && equipmentType.contains("_")) {
            List<String> list = Arrays.asList(equipmentType.split("_"));
            Long energyTypeId = Long.valueOf(list.get(0));
            if (ObjectUtil.isNotNull(energyTypeId)) {
                goodsIdList = this.baseMapper.getGoodsIdListByEnergyType(companyId, energyTypeId);
            }
        }

        // 处理异常
        if (CollectionUtil.isEmpty(goodsIdList))
            throw new Exception("当前公司没有任何【" + equipmentType + "】产品,请先维护产品");

        return goodsIdList;
    }

    @Override
    public GGoodsDTO getGoodsDetailByUuid(String uuid) throws Exception {
        if (StrUtil.isBlank(uuid)) {
            throw new Exception("请传入产品uuid");
        }
        // 查询产品主体
        QueryWrapper<GGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("uuid", uuid);
        GGoods gGoods = this.getOne(wrapper);
        if (ObjectUtil.isNull(gGoods)) {
            throw new Exception("未查询到产品信息");
        }
        return setGoodsDetailFields(gGoods);
    }

    @Override
    public GGoodsDTO getGoodsDetailSblx(String sblx, String companyId) throws Exception {
        if (StrUtil.isBlank(sblx) && StrUtil.isBlank(companyId)) {
            throw new Exception("请传入产品设备类型和公司id");
        }
        // 查询产品主体
        QueryWrapper<GGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("sblx", sblx).eq("companyId", companyId);
        GGoods gGoods = this.getOne(wrapper);
        if (ObjectUtil.isNull(gGoods)) {
            throw new Exception("未查询到产品信息");
        }
        return setGoodsDetailFields(gGoods);
    }

    @Override
    public GGoodsDTO getGoodsDetailByGoodsCode(String companyId, String goodsCode) throws Exception {
        if (StrUtil.isBlank(goodsCode)) {
            throw new Exception("请传入产品的设备型号");
        }
        // 查询产品主体
        QueryWrapper<GGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("goodsCode", goodsCode);
        wrapper.eq("companyId", companyId);
        wrapper.eq("isdelete", IS_DELETE_NO);
        wrapper.eq("enable", 1);
        GGoods gGoods = this.getOne(wrapper);
        if (ObjectUtil.isNull(gGoods)) {
            throw new Exception("未查询到产品详细信息");
        }
        return setGoodsDetailFields(gGoods);
    }

    @Override
    public List<GGoods> getGoodsByBrandId(String companyId, String brandId) throws Exception {
        if (StrUtil.isBlank(brandId)) {
            return Collections.emptyList();
        }
        QueryWrapper<GGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("brandId", brandId);
        wrapper.eq("companyId", companyId);
        wrapper.eq("isdelete", IS_DELETE_NO);
        wrapper.eq("enable", 1);
        return this.baseMapper.selectList(wrapper);
    }

    @Override
    public List<DeviceModelDTO> getDeviceModel(String companyId, String deviceModelId) throws Exception {
        return getDeviceModels(companyId, Arrays.asList(deviceModelId));
    }

    @Override
    public List<DeviceModelDTO> getDeviceModels(String companyId, List<String> deviceModelIdList) throws Exception {
        if (CollUtil.isEmpty(deviceModelIdList)) {
            return Collections.emptyList();
        }
        return this.baseMapper.getDeviceModel(companyId, deviceModelIdList);
    }

    @Override
    public Map<String, String> getGoodsMap(Set<String> sblxIdSet) {
        if (CollectionUtil.isEmpty(sblxIdSet)) {
            throw new MissBusinessParameterException("sblxIdSet must not empty");
        }

        QueryWrapper<GGoods> wrapper = new QueryWrapper<>();
        wrapper.select("sblx", "goodsName");
        wrapper.eq("isdelete", DeleteEnum._0.getKey());
        wrapper.in("sblx", sblxIdSet);

        List<GGoods> goodsList = this.baseMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(goodsList)) {
            return new HashMap<>();
        }

        Map<String, String> map = new HashMap<>();
        for (GGoods goods : goodsList) {
            map.put(goods.getSblx(), goods.getGoodsName());
        }

        return map;
    }

    @Override
    public List<InstallOrderEquipmentDTO> queryInstallOrderEquipmentInfo(Long workOrderId) {
        if (ObjectUtil.isNull(workOrderId)) {
            return Collections.emptyList();
        }
        return this.baseMapper.queryInstallOrderEquipmentInfo(workOrderId);
    }

    @Override
    public List<GGoodsDTO> getGoodsListBySblxId(String companyId, List<String> parts) {
        List<GGoodsDTO> gGoodsList = gGoodsMapper.getGoodsListBySblxId(companyId, parts);
        setResponseParams(gGoodsList, true);
        return gGoodsList;
    }

    @Override
    public List<ProductDTO> getGoods(List<String> productUuids) {
        if (CollUtil.isEmpty(productUuids)) {
            return Collections.emptyList();
        }

        return this.baseMapper.getGoodsByCodes(productUuids);
    }

    @Override
    public GGoodsDTO getGoodsDetailByBarCode(String companyId, String barCode) throws Exception {
        if (StrUtil.isBlank(barCode)) {
            return null;
        }
        // 根据商品条码查询产品
        QueryWrapper<GGoods> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(companyId)) {
            queryWrapper.eq("companyId", companyId);
        }
        queryWrapper.eq("goodsCode", barCode);
        queryWrapper.eq("isdelete", false);
        queryWrapper.last("limit 1");
        List<GGoods> goodsList = gGoodsMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(goodsList) || ObjectUtil.isNull(goodsList.get(0))) {
            return null;
        }
        // 转换返回值类型
        List<GGoodsDTO> gGoodsDTOS = CopyUtils.copyList(goodsList, GGoodsDTO.class);
        GGoodsDTO gGoodsDTO = gGoodsDTOS.get(0);
        // 处理能源类型
        if (ObjectUtil.isNotNull(gGoodsDTO.getEnergyType())) {
            ProductSeriesAndEnergyDTO energyTypeInfo = productSeriesAndEnergyService.getDetailById(gGoodsDTO.getEnergyType());
            if (ObjectUtil.isNotNull(energyTypeInfo)) {
                String energyTypeCodes = energyTypeInfo.getEnergyType();
                gGoodsDTO.setEnergyTypeCodeSet(StrUtil.isNotBlank(energyTypeCodes) ? new HashSet<>(Arrays.asList(energyTypeCodes.split(","))) : new HashSet<>());
            }
        }
        return gGoodsDTO;
    }

    // 设置产品详情的相关字段
    private GGoodsDTO setGoodsDetailFields(GGoods gGoods) {
        // 转换格式
        GGoodsDTO gGoodsDTO = new GGoodsDTO();
        BeanUtils.copyProperties(gGoods, gGoodsDTO);
        // 查询铭牌配置
        IsSblxNameplateConfigVO configVO = new IsSblxNameplateConfigVO();
        configVO.setDeviceModelId(String.valueOf(gGoodsDTO.getEnergyType()));
        PageData nameplateInfoPage = isSblxNameplateConfigService.getNameplateInfo(configVO);
        List<Object> list = new ArrayList<>();
        if (!Objects.isNull(nameplateInfoPage.getData()) && !Objects.isNull(nameplateInfoPage.getData().get("nameplateInfo"))) {
            list = (List<Object>) nameplateInfoPage.getData().get("nameplateInfo");
        }
        List<IsSblxNameplateConfigDTO> nameplateInfo = CopyUtils.copyList(list, IsSblxNameplateConfigDTO.class);
        // 根据铭牌配置查询产品物理参数
        if (CollectionUtil.isNotEmpty(nameplateInfo)) {
            // 查询物理参数
            List<String> fieldList = nameplateInfo.stream().map(IsSblxNameplateConfigDTO::getSblxField).collect(Collectors.toList());
            String sqlColumn = String.join(",", fieldList);
            Map<String, String> physicalParams = gGoodsMapper.getPhysicalParams(sqlColumn, gGoodsDTO);
            log.info("physicalParams:" + physicalParams);
            // 组装物理参数
            if (!Objects.isNull(physicalParams)) {
                nameplateInfo.stream().forEach(n -> {
                    n.setValue(physicalParams.get(n.getSblxField()));
                });
            } else {
                nameplateInfo.stream().forEach(n -> {
                    n.setValue("");
                });
            }
            gGoodsDTO.setFieldsParamList(nameplateInfo);
        }

        // 设置出参字段
        List<GGoodsDTO> goodsList = new ArrayList<>();
        goodsList.add(gGoodsDTO);
        setResponseParams(goodsList, true);

        return goodsList.get(0);
    }

    // 以【能源类型】体系查询产品分页
    public List<GGoodsDTO> getGoodsPageByEnergyType(GGoodsVO vo) throws Exception {
        Set<Long> productEnergyIdList = vo.getProductEnergyIdList();
        Set<Long> productBrandIdList = vo.getProductBrandIdList();

        // 查询品牌子节点id
        Set<Long> brandChildIds = new HashSet<>();
        if (CollectionUtil.isNotEmpty(productBrandIdList)) {
            for (Long brandId : productBrandIdList) {
                brandChildIds.addAll(productSeriesAndEnergyService.getAllChildIds(brandId, true));
            }
        }

        // 查询能源分类子节点id - 按能源分类的已配置【能源类型】的下级子节点查询
        QueryProductSeriesAndEnergyBO queryBO = new QueryProductSeriesAndEnergyBO();
        queryBO.setEnergyTypeList(vo.getEnergyTypeList());
        queryBO.setEnable(true);
        List<ProductSeriesAndEnergyDTO> productEnergyInfoList = productSeriesAndEnergyService.getEnergyClassification(queryBO);
        Set<Long> energyTypeChildIds = productSeriesAndEnergyService.handleEnergyIdList(productEnergyInfoList, productEnergyIdList);

        // 按能源分类的全部下级节点查询
//        if (CollectionUtil.isNotEmpty(productEnergyIdList)) {
//            for (Long energyClassificationId : productEnergyIdList) {
//                energyTypeChildIds.addAll(productSeriesAndEnergyService.getAllChildIds(energyClassificationId, true));
//            }
//        }

        // 如果品牌系列和能源分类都是空 - 返回空
        if (CollectionUtil.isEmpty(brandChildIds) && CollectionUtil.isEmpty(energyTypeChildIds)) {
            return Collections.emptyList();
        }

        // 组装参数
        vo.setCompanyId(vo.getOperateUserCompanyId());
        vo.setBrandChildIds(new ArrayList<>(brandChildIds));
        vo.setEnergyTypeChildIds(new ArrayList<>(energyTypeChildIds));

        Page<GGoodsDTO> page = new Page<>(vo.getPageid(), vo.getPagesize());
        List<GGoodsDTO> goodsList = gGoodsMapper.getGoodsPage(page, vo);
        // 设置出参字段
        setResponseParams(goodsList, true);

        return goodsList;
    }

    // 查询当前登录人所属公司的产品id
    private Set<String> queryMyCompanyProductId(List<Long> brandChildIds, String operateUserCompanyId) {
        Set<String> productUuidSet = new HashSet<>();
        if (StrUtil.isBlank(operateUserCompanyId)) {
            return productUuidSet;
        }

        QueryWrapper<GGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("uuid");
        queryWrapper.in("companyId", operateUserCompanyId);
        if (CollectionUtil.isNotEmpty(brandChildIds)) {
            queryWrapper.in("brand_id", brandChildIds);
        }
        List<GGoods> gGoods = this.baseMapper.selectList(queryWrapper);
        productUuidSet = gGoods.stream().map(GGoods::getUuid).collect(Collectors.toSet());

        return productUuidSet;
    }

    // 查询当前登录人所属公司的代理的产品id
    private Set<String> queryAgentGrantProductId(List<Long> brandChildIds, String operateUserCompanyId) {
        Set<String> productUuidSet = new HashSet<>();
        if (StrUtil.isBlank(operateUserCompanyId)) {
            return productUuidSet;
        }
        // 查询授权来的产品列表
        List<GGoods> grantProductNode = agentGrant.getGrantProductNode(operateUserCompanyId);
        if (CollectionUtil.isEmpty(grantProductNode)) {
            return productUuidSet;
        }
        // 获取授权来的产品的uuid集合
        if (CollectionUtil.isEmpty(brandChildIds)) {
            productUuidSet = grantProductNode.stream().map(GGoods::getUuid).collect(Collectors.toSet());
        } else {
            productUuidSet = grantProductNode.stream().filter(n -> brandChildIds.contains(n.getBrandId())).map(GGoods::getUuid).collect(Collectors.toSet());
        }

        return productUuidSet;
    }

    // 校验当前产品是否属于当前登录人所属公司
    private boolean checkProductBelongToCompany(String productUuid, String companyId) {
        GGoodsDTO productDetail = new GGoodsDTO();
        try {
            productDetail = this.getGoodsDetailByUuid(productUuid);
        } catch (Exception e) {
            log.error("查询产品信息失败,认为当前产品不属于当前登录人所属公司");
            return false;
        }
        return productDetail.getCompanyId().equals(companyId);
    }

}
